package cn.zcy.service.impl;

import cn.zcy.dao.AccountDao;
import cn.zcy.domain.Account;
import cn.zcy.service.AccountService;
import cn.zcy.until.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service("accountService")
public class AccountServiceImpl_old implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private TransactionManager transactionManager;

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {

    }

    /**
     * 转账业务
     *
     * @param sourceName
     * @param targeName
     * @param money
     */
    @Override
    public void transfer(String sourceName, String targeName, Double money) {
        try {
            //开启事务
            transactionManager.begin();
            //1.根据名称查询转出账户
            Account sourceAccount = accountDao.findByName(sourceName);
            //2.根据名称查询转入账户
            Account tagerAccount = accountDao.findByName(targeName);
            //3.转出账户减钱
            sourceAccount.setMoney(sourceAccount.getMoney() - money);
            //4.转入账户加钱
            tagerAccount.setMoney(tagerAccount.getMoney() + money);
            //5.更新转出账户
            accountDao.update(sourceAccount);
//            int b=1/0;
            //6.更新转入账户
            accountDao.update(tagerAccount);
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback();
        }finally {
            transactionManager.close();
        }
    }

    @Override
    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
